<!-- views/sales/commission/components/CommissionConfig.vue -->
<template>
  <el-card class="commission-config">
    <template #header>
      <div class="card-header">
        <span>提成规则配置</span>
        <el-button 
          type="primary" 
          :icon="Refresh" 
          @click="refreshConfig"
        >
          刷新配置
        </el-button>
      </div>
    </template>
    
    <el-form 
      :model="configForm" 
      :rules="configRules" 
      ref="configFormRef" 
      label-width="120px"
      @submit.prevent="saveConfig"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="基础提成比例" prop="baseRate">
            <el-input-number 
              v-model="configForm.baseRate" 
              :min="0" 
              :max="100" 
              :precision="2" 
              style="width: 100%"
            />
            <span class="unit">%</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="阶梯提成比例" prop="tieredRates">
            <el-button @click="showTieredRatesDialog" link>
              配置阶梯提成
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="生效日期" prop="effectiveDate">
            <el-date-picker
              v-model="configForm.effectiveDate"
              type="date"
              placeholder="选择生效日期"
              style="width: 100%"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="适用范围" prop="scope">
            <el-select v-model="configForm.scope" placeholder="请选择适用范围" style="width: 100%">
              <el-option label="全部销售人员" value="all" />
              <el-option label="指定销售人员" value="specific" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item v-if="configForm.scope === 'specific'" label="指定人员" prop="salespersons">
        <el-select 
          v-model="configForm.salespersons" 
          multiple 
          placeholder="请选择销售人员" 
          style="width: 100%"
        >
          <el-option
            v-for="person in allSalespersons"
            :key="person.id"
            :label="person.name"
            :value="person.id"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="备注" prop="remark">
        <el-input 
          v-model="configForm.remark" 
          type="textarea" 
          placeholder="请输入备注说明"
        />
      </el-form-item>
      
      <div class="form-actions">
        <el-button type="primary" @click="saveConfig" :loading="submitting">
          保存配置
        </el-button>
        <el-button @click="resetConfig">
          重置
        </el-button>
      </div>
    </el-form>
    
    <!-- 阶梯提成配置对话框 -->
    <el-dialog
      v-model="tieredRatesDialogVisible"
      title="阶梯提成配置"
      width="600px"
    >
      <el-table :data="tieredRates" style="width: 100%">
        <el-table-column label="销售额区间(万元)" min-width="200">
          <template #default="scope">
            <el-input-number 
              v-model="scope.row.minAmount" 
              :min="0" 
              :precision="2" 
              placeholder="最小值"
              size="small"
            />
            <span class="separator">-</span>
            <el-input-number 
              v-model="scope.row.maxAmount" 
              :min="0" 
              :precision="2" 
              placeholder="最大值"
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column label="提成比例" min-width="120">
          <template #default="scope">
            <el-input-number 
              v-model="scope.row.rate" 
              :min="0" 
              :max="100" 
              :precision="2" 
              size="small"
            />
            <span class="unit">%</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="scope">
            <el-button 
              @click="removeTieredRate(scope.$index)" 
              type="danger" 
              size="small"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 10px;">
        <el-button @click="addTieredRate" type="primary">添加区间</el-button>
      </div>
      
      <template #footer>
        <el-button @click="tieredRatesDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveTieredRates">确定</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'

interface Salesperson {
  id: number
  name: string
}

interface TieredRate {
  minAmount: number
  maxAmount: number
  rate: number
}

interface CommissionConfig {
  baseRate: number
  effectiveDate: string
  scope: string
  salespersons: number[]
  remark: string
}

const props = defineProps<{
  modelValue: CommissionConfig
  allSalespersons: Salesperson[]
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: CommissionConfig): void
  (e: 'save', config: CommissionConfig): void
  (e: 'refresh'): void
}>()

const configFormRef = ref<FormInstance>()
const submitting = ref(false)
const tieredRatesDialogVisible = ref(false)

const configForm = ref<CommissionConfig>({
  baseRate: 0,
  effectiveDate: '',
  scope: 'all',
  salespersons: [],
  remark: ''
})

const tieredRates = ref<TieredRate[]>([
  { minAmount: 0, maxAmount: 100, rate: 5 },
  { minAmount: 100, maxAmount: 500, rate: 8 },
  { minAmount: 500, maxAmount: 0, rate: 12 }
])

const configRules = ref<FormRules>({
  baseRate: [
    { required: true, message: '请输入基础提成比例', trigger: 'blur' }
  ],
  effectiveDate: [
    { required: true, message: '请选择生效日期', trigger: 'change' }
  ]
})

// 监听传入的配置值
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    configForm.value = { ...newVal }
  }
}, { immediate: true })

const refreshConfig = () => {
  emit('refresh')
}

const saveConfig = async () => {
  if (!configFormRef.value) return
  
  await configFormRef.value.validate((valid) => {
    if (valid) {
      submitting.value = true
      try {
        emit('save', { ...configForm.value })
        ElMessage.success('提成规则配置保存成功')
      } catch (error) {
        ElMessage.error('保存失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

const resetConfig = () => {
  configForm.value = { ...props.modelValue }
}

const showTieredRatesDialog = () => {
  tieredRatesDialogVisible.value = true
}

const addTieredRate = () => {
  tieredRates.value.push({
    minAmount: 0,
    maxAmount: 0,
    rate: 0
  })
}

const removeTieredRate = (index: number) => {
  tieredRates.value.splice(index, 1)
}

const saveTieredRates = () => {
  tieredRatesDialogVisible.value = false
  ElMessage.success('阶梯提成配置已保存')
}
</script>

<style scoped>
.commission-config {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.unit {
  margin-left: 5px;
}

.separator {
  margin: 0 5px;
}

.form-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>